<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*
            平衡二叉树：左右子树的高度差小于等于1。
            思路：遍历每个节点，通过getDepth获取其左右子树的高度，然后判断差值
             */
            var isBalanced = function (root) {
                if (!root) return true
                let flag = true
                function preOrder(root) {
                    if (!root) return
                    let left = getDepth(root.left)
                    let right = getDepth(root.right)
                    if (Math.abs(left - right) > 1) {
                        return (flag = false)
                    }
                    preOrder(root.left)
                    preOrder(root.right)
                }
                preOrder(root)
                return flag
                function getDepth(root) {
                    if (!root) return 0
                    return Math.max(getDepth(root.left), getDepth(root.right)) + 1
                }
            }
        </script>
    </body>
</html>
